from django.shortcuts import render, HttpResponse, redirect

from smart.utils.md5 import md5

from smart import models


def register(request):
    """
    注册
    :param request:
    :return:
    """
    if request.method == 'GET':
        return render(request, 'user/register.html')
    username = request.POST.get('username')
    password = request.POST.get('password')
    telephone = request.POST.get('telephone')
    form_error = '账号错误或密码错误'

    data = {
        'username': username,
        'password': md5(password),
        'telephone': telephone,

    }
    if len(password) <= 6:
        return render(request, 'user/register.html', {'form_error': form_error})

    if len(data) != 3:
        return render(request, 'user/register.html', {'form_error': form_error})
    exist = models.UserInfo.objects.filter(username=username).exists()
    if exist:
        return render(request, 'user/register.html', {'form_error': form_error})

    try:
        user_obj = models.UserInfo.objects.create(**data)
        return redirect('login')
    except Exception:
        return render(request, 'user/register.html', {'form_error': form_error})


def user_login(request):
    """
    登录
    :param request:
    :return:
    """
    if request.method == 'GET':
        return render(request, 'user/login.html')

    form_error = '账号错误或密码错误'

    # 查询当前用户是否存在
    username = request.POST.get('username')
    password = request.POST.get('password')
    # 查询当前用户是否存在
    user_query = models.UserInfo.objects.filter(username=username, password=md5(password), is_active=True)
    # 如果不存在
    if not user_query.exists():
        return render(request, 'user/login.html', {'form_error': form_error})
    # 修改状态
    user_obj = user_query.first()
    # 存session
    request.session['user_dic'] = {'id': user_obj.id, 'username': user_obj.username}
    return redirect('home')


def login_out(request):
    """
    退出
    :param request:
    :return:
    """
    # 退出
    user_id = request.session.get('user_dic')['id']
    user_obj = models.UserInfo.objects.get(id=user_id)
    # print(user_obj, '------------')
    user_obj.is_login = False
    user_obj.save()
    # 清楚session
    request.session.clear()
    return redirect('login')
